package com.xiaoma.mvi

import android.os.Bundle
import android.transition.TransitionInflater
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import androidx.navigation.fragment.findNavController
import com.xiaoma.mvi.databinding.FragmentSubBinding
import com.xiaoma.mvi.func.BindingFragment
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class SubFragment : BindingFragment<FragmentSubBinding>() {

    private val vm by viewModels<Vm>()

    override fun onResume() {
        super.onResume()
        enterTransition = TransitionInflater.from(requireContext())
            .inflateTransition(R.transition.fragment_exit)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewLifecycleOwner.lifecycleScope.launch {
            vm.countdownFlow.collect {
                binding.tvCountdown.text = "${it}秒后返回"
                if (it == 0) {
                    findNavController().navigateUp()
                }
            }
        }
    }

    class Vm : ViewModel() {

        private val _countdownFlow = MutableStateFlow(3)
        val countdownFlow = _countdownFlow.asStateFlow()

        init {
            viewModelScope.launch {
                delay(1000)
                _countdownFlow.update { 2 }
                delay(1000)
                _countdownFlow.update { 1 }
                delay(1000)
                _countdownFlow.update { 0 }
            }

        }


    }

}